﻿using SimpleORM.Extensions;
using SqlSugar.IOC;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SimpleORM.Service
{
    public class BaseService<T> : SimpleClient<T> where T : class, new()
    {
        protected ITenant itenant = null;//多租户事务
        public BaseService(ISqlSugarClient context = null) : base(context)
        {
            var configId = typeof(T).GetCustomAttribute<TenantAttribute>().configId;
            //根据特性指定具体使用哪个库
            if (configId != null)
            {
                Context = DbScoped.SugarScope.GetConnectionScope(configId);//根据类传入的ConfigId自动选择
            }
            else
            {
                Context = context ?? DbScoped.SugarScope.GetConnectionScope(0);//没有默认db0
            }
            itenant = DbScoped.SugarScope;
            Context.Aop.OnError = (exp) =>//SQL报错
            {
                Console.ForegroundColor = ConsoleColor.Red;
                var log = UtilMethods.GetNativeSql(exp.Sql, (SugarParameter[])exp.Parametres);
                Console.Write(log + "\n");
            };
            Context.Aop.OnExecutingChangeSql = (sql, pars) => //可以修改SQL和参数的值
            {
                return new KeyValuePair<string, SugarParameter[]>(sql, pars);
            };

            Context.Aop.OnLogExecuted = (sql, p) =>
            {
                //执行时间超过1秒
                if (Context.Ado.SqlExecutionTime.TotalSeconds > 1)
                {
                    //代码CS文件名
                    var fileName = Context.Ado.SqlStackTrace.FirstFileName;
                    //代码行数
                    var fileLine = Context.Ado.SqlStackTrace.FirstLine;
                    //方法名
                    var FirstMethodName = Context.Ado.SqlStackTrace.FirstMethodName;
                }
                Console.ForegroundColor = ConsoleColor.Green;
                var log = UtilMethods.GetSqlString(SqlSugar.DbType.SqlServer, sql, p);
                Console.Write(log + "\n");
            };
        }

        public long NewID()
        {
            try
            {
                SnowFlakeSingle.WorkId = AppSettings.GetConfig("SnowFlakeSingle:WorkerId").IsEmpty() ? AppSettings.GetConfig("SnowFlakeSingle:WorkerId").ToInt() : 1;
                SnowFlakeSingle.DatacenterId = AppSettings.GetConfig("SnowFlakeSingle:DatacenterId").IsEmpty() ? AppSettings.GetConfig("SnowFlakeSingle:DatacenterId").ToInt() : 1;
                return SnowFlakeSingle.Instance.NextId();
            }
            catch
            {
                var ran = new Random();
                return ran.Next(16, 18);
            }
        }
    }
}
